package juan.happyge.plugin.myi.view.page;

import juan.happyge.plugin.myi.config.BookConfig;
import juan.happyge.plugin.myi.config.ConfigManage;
import juan.happyge.plugin.myi.pojo.book.ChapterPojo;
import juan.happyge.plugin.myi.service.book.BookService;
import juan.happyge.plugin.myi.view.factory.BookViewFactory;
import org.apache.commons.collections.CollectionUtils;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Vector;
import java.util.stream.Collectors;

public class BookChapterView {

    public JList listChapter;
    public JPanel panelBookChapter;
    private List<ChapterPojo> chapterPojoList;

    public BookChapterView(){
        listChapter.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        listChapter.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                ChapterPojo chapterPojo = chapterPojoList.get(listChapter.getSelectedIndex());
                BookViewFactory.bookView.jumpChapter(chapterPojo);
            }
        });
        initBookChapter();
    }

    public void initBookChapter(){
        //添加小说章节
        List<ChapterPojo> bookChapters = BookService.getBookChapters();
        if(CollectionUtils.isEmpty(bookChapters)){
            chapterPojoList = new ArrayList<>();
        }
        this.chapterPojoList = bookChapters;
        List<String> collect = chapterPojoList.stream().map(ChapterPojo::getName).collect(Collectors.toList());
        listChapter.setListData(new Vector<String>(collect));

        //定位当前阅读章节
        BookConfig bookConfig = ConfigManage.getInstance().getBookConfig();
        ChapterPojo currentChapter = BookService.getChapterInfo(bookConfig.getLineIndex());
        if(Objects.nonNull(currentChapter)){
            listChapter.setSelectedIndex(currentChapter.getIndex());
            //滚动到所选章节
            listChapter.ensureIndexIsVisible(listChapter.getSelectedIndex());
        }
    }

}
